package com.m1905hd.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.service.FilmTypeService
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam

/**
 * Created by sunhao on 2016/12/16.
 */
@Controller
@RequestMapping(value = "filmType")
class FilmTypeController {

    @Autowired
    FilmTypeService filmTypeService

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    def showList() {
        return "film/filmTypeList"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            String title
    ) {
        pageIndex = pageIndex + 1
        def query = [] as BasicDBObject
        if (!StringUtils.isEmpty(title)) {
            query.append("title", ~/${title}/)
        }
        Page page = this.filmTypeService.list(query, new BasicDBObject("created", -1), null, pageIndex, limit)
        [results: page.count, rows: page.data]
    }

    @RequestMapping(value = "edit", method = RequestMethod.POST)
    def edit(
            @RequestParam(defaultValue = "0") int id, String title, String info
    ) {
        if (StringUtils.isEmpty(info)) {
            info = "无描述"
        }
        def obj = [title: title, info: info] as BasicDBObject
        if (id == 0) {
            obj.created = System.currentTimeMillis()
            id = this.filmTypeService.getCurrentId()
        }
        this.filmTypeService.update(id, obj)
        return "redirect:list"
    }

    @RequestMapping("delete.json")
    def del(String ids) {
        ids.split(",").each {
            if (!StringUtils.isEmpty(it)) {
                this.filmTypeService.del(it as int)
            }

        }
        return [code: JSONCode.SUCCESS.code]
    }


}
